﻿using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Mapping;
using CCTool.Scripts.Manager;
using CCTool.Scripts.ToolManagers;
using CCTool.Scripts.ToolManagers.Extensions;
using CCTool.Scripts.ToolManagers.Managers;
using CCTool.Scripts.ToolManagers.Windows;
using SharpCompress.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CCTool.Scripts.GHApp.QT
{
    /// <summary>
    /// Interaction logic for IntersectStatistics.xaml
    /// </summary>
    public partial class IntersectStatistics : ArcGIS.Desktop.Framework.Controls.ProWindow
    {
        // 工具设置标签
        readonly string toolSet = "SDStatistic";
        public IntersectStatistics()
        {

            InitializeComponent();

            // 初始化参数选项
            mjNum.Text = BaseTool.ReadValueFromReg(toolSet, "mjDigit", "6");
            zbNum.Text = BaseTool.ReadValueFromReg(toolSet, "zbDigit", "6");

            // 初始化combox
            combox_unit.Items.Add("平方米");
            combox_unit.Items.Add("公顷");
            combox_unit.Items.Add("平方公里");
            combox_unit.Items.Add("亩");
            combox_unit.SelectedIndex = 1;

            combox_pa.Items.Add("百分数");
            combox_pa.Items.Add("小数");
            combox_pa.SelectedIndex = 0;

        }

        // 定义一个进度框
        private ProcessWindow processwindow = null;
        string tool_name = "相交占比分析";

        private async void btn_go_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 获取默认数据库
                var def_gdb = Project.Current.DefaultGeodatabasePath;
                // 获取要素
                string origin = combox_origin.ComboxText();
                string unit = combox_unit.Text;
                string pa = combox_pa.Text;

                int mjDigit = mjNum.Text.ToInt();
                int zbDigit = zbNum.Text.ToInt();

                Dictionary<string, string> layerPairs = GetDgContent();


                // 单位系数设置
                double unit_xs = unit switch
                {
                    "平方米" => 1,
                    "公顷" => 10000,
                    "平方公里" => 1000000,
                    "亩" => 666.66667,
                    _ => 1,
                };

                // 百分数系数
                double pa_xs = pa switch
                {
                    "百分数" => 100,
                    "小数" => 1,
                    _ => 1,
                };

                // 判断参数是否选择完全
                if (origin == "" || layerPairs.Count == 0)
                {
                    MessageBox.Show("有必选参数为空！！！");
                    return;
                }

                // 写入本地
                BaseTool.WriteValueToReg(toolSet, "mjDigit", mjDigit);
                BaseTool.WriteValueToReg(toolSet, "zbDigit", zbDigit);

                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);

                Close();

                await QueuedTask.Run(() =>
                {
                    pw.AddMessageStart("检查数据");

                    // 检查数据
                    List<string> errs = CheckData();
                    // 打印错误
                    if (errs.Count > 0)
                    {
                        foreach (var err in errs)
                        {
                            pw.AddMessageMiddle(10, err, Brushes.Red);
                        }
                        return;
                    }

                    string intersect = $@"{def_gdb}\intersect";
                    string out_table = $@"{def_gdb}\out_table";
                    string field = "标记";

                    // 分图层处理
                    foreach (var layerPair in layerPairs)
                    {
                        // 图层和标记字段
                        string lyName = layerPair.Key;
                        string aliasName = layerPair.Value;
                        string mjField = aliasName + "MJ";
                        string zbField = aliasName + "ZB";

                        string aliasString = lyName[(lyName.LastIndexOf('\\') + 1)..].Split('：')[0];
                        string mjAliasName = aliasString + "面积";
                        string zbAliasName = aliasString + "占比";

                        pw.AddMessageMiddle(80 / layerPairs.Count, $"     处理图层：{lyName}, 标记字段：{mjField}， {zbField}", Brushes.Gray);

                        List<string> lines = new List<string>() { origin, lyName };

                        // 标记一个ID字段
                        string oid = origin.TargetIDFieldName();

                        Arcpy.AddField(origin, field, "LONG");
                        Arcpy.CalculateField(origin, field, @$"!{oid}!");

                        List<string> in_fcs = new List<string>() { origin, lyName };

                        Arcpy.Intersect(in_fcs, intersect);

                        // 计算面积
                        Arcpy.AddField(intersect, "面积标记", "DOUBLE");
                        Arcpy.CalculateField(intersect, "面积标记", "!shape.area!");

                        // 先判断一下，如果有MJ字段，就先删除
                        if (GisTool.IsHaveFieldInTarget(origin, mjField))
                        {
                            Arcpy.DeleteField(origin, mjField);
                        }
                        // 先判断一下，如果有MJ字段，就先删除
                        if (GisTool.IsHaveFieldInTarget(origin, zbField))
                        {
                            Arcpy.DeleteField(origin, zbField);
                        }

                        // 汇总并连接字段
                        Arcpy.Statistics(intersect, out_table, "面积标记 SUM", field);
                        Arcpy.AlterField(out_table, "SUM_面积标记", mjField, mjAliasName);

                        Arcpy.JoinField(origin, oid, out_table, field, new List<string>() { mjField });

                        // 计算占比
                        Arcpy.AddField(origin, zbField, "DOUBLE", zbAliasName);
                        Arcpy.CalculateField(origin, zbField, $"round(!{mjField}!/!Shape.Area!*{pa_xs},{zbDigit})");
                        Arcpy.CalculateField(origin, mjField, $"round(!{mjField}!/{unit_xs},{mjDigit})");

                    }

                    // 删除中间字段
                    Arcpy.Delect(intersect);
                    Arcpy.Delect(out_table);
                    Arcpy.DeleteField(origin, field);

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private void btn_help_Click(object sender, RoutedEventArgs e)
        {
            string url = "https://blog.csdn.net/xcc34452366/article/details/140240696";
            UITool.Link2Web(url);
        }


        private void combox_origin_DropDown(object sender, EventArgs e)
        {
            UITool.AddFeatureLayersToComboxPlus(combox_origin);
        }

        private void combox_origin_DropClose(object sender, EventArgs e)
        {
            // 更新表格内容
            UpdataDG();
        }

        // 定义一个空包
        List<LayerAtt> layerAtt = new List<LayerAtt>();

        private void btn_select_Click(object sender, RoutedEventArgs e)
        {
            if (dg.Items.Count == 0)
            {
                MessageBox.Show("列表内没有内容！");
                return;
            }

            // 定义一个新包
            List<LayerAtt> layerAtt2 = layerAtt;

            foreach (var item in layerAtt2)
            {
                item.IsCheck = true;
            }

            // 绑定
            dg.ItemsSource = layerAtt2;
            // 刷新
            dg.Items.Refresh();
        }

        private void btn_unSelect_Click(object sender, RoutedEventArgs e)
        {
            if (dg.Items.Count == 0)
            {
                MessageBox.Show("列表内没有内容！");
                return;
            }

            // 定义一个新包
            List<LayerAtt> layerAtt2 = layerAtt;

            foreach (var item in layerAtt2)
            {
                item.IsCheck = false;

            }

            // 绑定
            dg.ItemsSource = layerAtt2;
            // 刷新
            dg.Items.Refresh();
        }

        // 更新表格内容
        private async void UpdataDG()
        {
            try
            {
                string origin = combox_origin.ComboxText();

                // 定义一个空包
                List<LayerAtt> layerAtt2 = new List<LayerAtt>();

                // 获取当前地图
                Map map = MapView.Active.Map;
                // 获取所有要素图层
                Dictionary<FeatureLayer, string> featureLayers = await QueuedTask.Run(() =>
                {
                    return map.AllFeatureLayersDic();
                });


                // 添加数据
                foreach (var featureLayer in featureLayers)
                {
                    FeatureLayer fl = featureLayer.Key;
                    string lyName = featureLayer.Value;

                    GeometryType geoType = await QueuedTask.Run(() =>
                    {
                        return lyName.TargetGeoType();
                    });

                    if (lyName == origin) { continue; }    // 原始图层不参与相交计算
                    if (geoType != GeometryType.Polygon) { continue; }    // 不是面要素就跳过

                    string fullPinyin = BaseTool.ChineseToPinyin(lyName, 5);
                    string aliasName = fullPinyin[(fullPinyin.LastIndexOf('\\') + 1)..].Split('：')[0];


                    layerAtt2.Add(new LayerAtt()
                    {
                        IsCheck = false,
                        LayerName = lyName,
                        AliasName = aliasName,
                    });
                }
                // 绑定
                dg.ItemsSource = layerAtt2;

                // 赋值
                layerAtt = layerAtt2;

            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        // 获取表格内容
        private Dictionary<string, string> GetDgContent()
        {
            // 获取对应字段列表
            Dictionary<string, string> layerPairs = new Dictionary<string, string>();

            for (int i = 0; i < dg.Items.Count; i++)
            {
                // 获取选择框
                CheckBox item_isCheck = (CheckBox)dg.GetCell(i, 0).Content;
                bool isCheck = (bool)item_isCheck.IsChecked;
                // 获取目标字段
                TextBlock item_lyName = (TextBlock)dg.GetCell(i, 1).Content;
                string lyName = item_lyName.Text;
                // 获取来源字段
                TextBlock item_aliasName = (TextBlock)dg.GetCell(i, 2).Content;
                string aliasName = item_aliasName.Text;
                // 如果是选中状态，就加到列表中
                if (isCheck)
                {
                    layerPairs.Add(lyName, aliasName);
                }
            }

            return layerPairs;
        }

        private List<string> CheckData()
        {
            List<string> result = new List<string>();


            return result;
        }


    }

    class LayerAtt
    {
        public bool IsCheck { get; set; }
        public string LayerName { get; set; }
        public string AliasName { get; set; }
    }
}
